-module(cus_token_redis).
-author("ShenDatian").

-include("cus.hrl").
-include("logger.hrl").
-include("ejabberd.hrl").
%% API
-export([start/5]).

-export([
    get_user_token/1
        ]).


-define(PROCNAME, 'cus_token_redis_').


start(Host, Port, DB, Pwd, Size) ->
    lists:foreach(fun(Index) ->
                          case eredis:start_link(Host, Port, DB, Pwd) of
                              {ok, Client} ->
                                  ProcName = get_proc_name(Index),
                                  register(ProcName, Client),
                                  {ok, Client};
                              {error, _} = Err ->
                                  Err
                          end
                  end, lists:seq(1, Size)),
    ?INFO_MSG("cus token redis start success", []).


get_proc_name(Index) ->
    Name = erlang:atom_to_list(?PROCNAME) ++ erlang:integer_to_list(Index),
    erlang:list_to_atom(Name).


get_redis_proc(Key) ->
    Size = cus_config:token_redis_size(),
    Index = erlang:phash(Key, Size),
    get_proc_name(Index).


get_user_token(Uid) ->
    ProcName = get_redis_proc(Uid),
    ?list(safe_q(ProcName, ["GET", "idBindToken_" ++ Uid])).
    

safe_q(ProcName, Cmd) ->
    case whereis(ProcName) of
        undefined ->
            [Host, Port, DB, Pwd, _Size] = cus_config:token_redis(),
            case eredis:start_link(?list(Host), Port, DB, ?list(Pwd)) of
                {ok, Client} ->
                    register(ProcName, Client),
                    case eredis:q(ProcName, Cmd) of
                        {ok, undefined} ->
                            <<>>;
                        {ok, V} ->
                            V;
                        _Err -> <<>>
                    end;
                {error, Err} ->
                    ?ERROR_MSG("Failed to start redis client: ~p", [Err]),
                    <<>>
            end;
        _ ->
            case eredis:q(ProcName, Cmd) of
                {ok, undefined} ->
                    <<>>;
                {ok, V} ->
                    V;
                _Err -> <<>>
            end
    end.
    


